package com.longrise.android.loaddata;

import android.util.Log;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by xkj on 2016/3/21.
 * 专为下载准备的线程池
 */
public class LoadDataThreadPool {

    /** 总共多少任务（根据CPU个数决定创建活动线程的个数,这样取的好处就是可以让手机承受得住） */
    private static final int CORE_POOL_SIZE = 5;
    private static final String TAG = "LoadDataThreadPool";

    private static int MAX_DOWNLOADING_TASK = 5;
    // 线程池
    private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAX_DOWNLOADING_TASK, 30, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(2000));
    private static Map<Runnable, Future<?>> map = new HashMap<Runnable, Future<?>>();
    private LoadDataThreadPool (){

    }

    /**
     * 从线程池中抽取线程，执行指定的Runnable对象
     * @param runnable
     */
    public static void execute(Runnable runnable)
    {
        //threadPool.execute(runnable);
        Future<?> submit = threadPool.submit(runnable);
        map.put(runnable, submit);
    }

    public static void remove(Runnable runnable)
    {
        Future<?> submit = (Future<?>) map.get(runnable);
        if(submit!=null){
            submit.cancel(true);
        }
    }

}
